package cn.edu.jxau.core.web;

import cn.edu.jxau.core.ApplicationContext;
import cn.edu.jxau.core.annotation.Action;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Desc:一个转发器，构建请求与处理的逻辑映射
 * ------------------------------------
 * Author:fulei04@meituan.com
 * Date:2017/12/17
 * Time:下午2:21
 */
public class Dispatcher {

    private static final Map<Request,Handler> ACTION_MAP = new HashMap<>();

    static {

        Set<Class> controllerSet = ApplicationContext.getControllers();
        for(Class controller : controllerSet) {
            Method[] methodArr = controller.getDeclaredMethods();
            if(methodArr == null) {
                continue;
            }
            for(Method method : methodArr) {
                if(method.isAnnotationPresent(Action.class)) {
                    Action action = method.getAnnotation(Action.class);
                    String actionValue = action.value();
                    if(!actionValue.matches("\\w+:/\\w*")) {
                        throw new RuntimeException("Action配置异常："+actionValue);
                    }
                    String[] arr = actionValue.split(":");
                    String requestMethod = arr[0].toUpperCase();
                    String requestURL = arr[1];
                    ACTION_MAP.put(new Request(requestMethod,requestURL),new Handler(controller,method));
                }
            }
        }
    }

    public Handler getHandler(String requestMethod,String requestURL) {
        return ACTION_MAP.get(new Request(requestMethod,requestURL));
    }
}
